<template>
  <!-- #ifdef H5 -->
  <uni-nav-bar title="我的购物车" left-icon="left" @clickLeft="navBack" :fixed="true" statusBar :rightText="show?'退出管理':'管理'"
    @clickRight="supervise()"></uni-nav-bar>
  <!-- #endif -->
  <!-- #ifndef H5 -->
  <uni-nav-bar title="我的购物车" left-icon="left" @clickLeft="navBack" :fixed="true" statusBar></uni-nav-bar>
  <view class="package flex-end"><text @click="supervise()">{{show?'退出管理':'管理'}}</text></view>
  <!-- #endif -->
  <view class="package" v-for="(item,index) in carAll" :key='item.id' style="padding:20rpx 10rpx">
    <view class="packageLsit">
      <uni-icons :type="ShoppList.indexOf(item.store_id)!=-1?'checkbox-filled':'circle'" size="22"
        :color="ShoppList.indexOf(item.store_id)!=-1?'#3EA2FF':'#666'"
        @click="storeShop(item.store_id,item.store_name)">
      </uni-icons>
      <image src="../../static/groupBenefits/shop.png" mode="" style="margin-left: 10rpx;"></image>
      <text @click="navTo('shopp/Shopkeeper?id='+item.store_id)">{{item.store_name}}</text>
      <uni-icons type="forward" size="20" color="#666"></uni-icons>
    </view>
    <view v-for="(items,indexs) in item.goods_list" :key='indexs' style="display: flex;align-items: center;">
      <uni-icons type="circle" size="22" color="#666" style="margin: 0px 10rpx;"
        @click="commodity(item.store_id,items.id,items.price,items.oprice,items.goods_nums,item.store_name)"
        v-if="ShoppingList.length<1">
      </uni-icons>
      <uni-icons v-else
        :type="ShoppingList.find(as=>as.store_id==item.store_id)&&ShoppingList.find(as=>as.store_id==item.store_id).goods_list.indexOf(items.id)!=-1?'checkbox-filled':'circle'"
        size="22"
        :color="ShoppingList.find(as=>as.store_id==item.store_id)&&ShoppingList.find(as=>as.store_id==item.store_id).goods_list.indexOf(items.id)!=-1?'#3EA2FF':'#666'"
        style="margin: 0px 10rpx;"
        @click="commodity(item.store_id,items.id,items.price,items.oprice,items.goods_nums,item.store_name)">
      </uni-icons>
      <ShopList :type="'car'" :shopAll="items" :show="true" @ModifyCart="ModifyCart" :datas="'car'" :width="'650'">
      </ShopList>
    </view>
  </view>
  <view class="column fillings" v-if="carAll.length<1" style="height:80vh">
    <image :src="Empty"></image>
    <text @click="redirectTo('index/shopp')" v-if="Useridentity=='1'">去添加商品~</text>
  </view>
  <ShopBot :title="title" :show="show" :Select="Select" @SelectAll="SelectAll" @submit="submit" :total="total"
    :Discount="Discount">
  </ShopBot>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { errorToast, successToast, showLoading } from '@/utils/prompt';
  import { navBack, navTo, redirectTo } from '@/utils/navigator';
  import ShopBot from '@c/groupBenefits/shopBot.vue';
  import ShopList from '@c/groupBenefits/miniShop.vue';
  import { Empty } from '@/utils/Static';
  import { toPublish } from '@mqtt';
  import { onShow } from '@dcloudio/uni-app';
  import { carList } from '@/gql/shop';
  import { getDriverID } from '@/stores/driverID';
  /**
   * 购物车
   * @param driver_id  用户ID
   * @param Useridentity  用户身份判断
   * @param show  调整底部按钮状态
   * @param title  底部按钮文字调整
   */
  const driver_id = getDriverID();
  const Useridentity = uni.getStorageSync('Useridentity');
  const show = ref(false);
  const title = ref('结算');
  const Select = ref(false);
  const shopText = ref('');

  const carAll = ref([]);

  const total = ref(0);
  const Discount = ref(0);

  const ShoppList = ref([]);
  const ShoppingList = ref([]);

  const repeat = ref(true); //放重复点击
  onShow(() => {
    total.value = 0;
    Discount.value = 0;
    carAll.value = [];
    ShoppList.value = [];
    ShoppingList.value = [];
    init('1');
  });
  /**
   * 获取
   */
  function init(num : any) {
    const payload = {
      query: carList,
      variables: {
        driver_id,
      },
    };
    toPublish('ql/store/cateGoodsList', payload, (obj : any) => {
      const { cart_goods_list } = obj.data;
      carAll.value = cart_goods_list;
      if (num.id) {
        moneyFor(num);
      }
    });
  }
  /**
   * @param {String} id 店铺iD
   * @param {String} name 店铺名
   * 选择店铺
   */
  function storeShop(id : number, name : string) {
    console.log(JSON.stringify(ShoppingList.value) + '0');
    const goodsList = carAll.value.filter((item) => item.store_id == id)[0].goods_list;
    shopText.value = name;
    if (ShoppList.value.length > 0 && ShoppList.value.indexOf(id) == -1 && !show.value) {
      errorToast('当前购物车只能购买同一家商品');
      return;
    }
    if (ShoppList.value.indexOf(id) == -1) {
      console.log('当前店铺不存在');
      ShoppList.value.push(id);
      if (ShoppingList.value.length > 0) {
        //当店铺商品存在时
        ShopMerchandise(goodsList, id);
      } else {
        console.log('都为空时直接加入店铺与店铺全部商品');
        var goods = [];
        goodsList.forEach((as : any) => {
          goods.push(as.id);
        });
        var obj = { store_id: id, goods_list: goods };
        ShoppingList.value.push(obj);
        goodsList.map((item : any) => {
          total.value = total.value + item.price * item.goods_nums;
          Discount.value = Discount.value + (item.oprice - item.price) * item.goods_nums;
          jsFlow();
        });
        if (ShoppList.value.length == carAll.value.length) {
          Select.value = true;
        } else {
          Select.value = false;
        }
      }
    } else {
      // 删除当前店铺以及金额
      DeleteAmount(goodsList, id);
    }
  }
  /**
   * @param {Object} goodsList 当前店铺的商品
   * @param {Object} id  当前店铺ID
   * 当店铺商品存在时
   */
  function ShopMerchandise(goodsList : any, id : number) {
    console.log('当店铺商品存在时33333333333333');
    ShoppingList.value.map((item) => {
      console.log(item);
      if (item.store_id == id) {
        console.log('当前店铺存在加入店铺与店铺全部商品计算价格');
        item.goods_list.map((items : any) => {
          goodsList.map((as : any) => {
            if (as.id != items) {
              item.goods_list.push(as.id);
              total.value = total.value + as.price * as.goods_nums;
              Discount.value = Discount.value + (as.oprice - as.price) * as.goods_nums;
              jsFlow();
            }
          });
        });
      } else {
        if (item.store_id != id) {
          var goods = [];
          goodsList.forEach((as : any) => {
            goods.push(as.id);
          });
          var obj = { store_id: id, goods_list: goods };
          ShoppingList.value.push(obj);
          goodsList.map((item : any) => {
            total.value = total.value + item.price * item.goods_nums;
            Discount.value = Discount.value + (item.oprice - item.price) * item.goods_nums;
            jsFlow();
          });
          if (ShoppList.value.length == carAll.value.length) {
            Select.value = true;
          } else {
            Select.value = false;
          }
        }
      }
    });
  }
  /**
   * @param {Object} goodsList 当前店铺的商品
   * @param {Object} id  当前店铺ID
   * 删除当前店铺以及金额
   */
  function DeleteAmount(goodsList : any, id : number) {
    Select.value = false;
    goodsList.map((as:any) => {
      total.value = total.value - as.goods_nums * as.price;
      Discount.value = Discount.value - +(as.oprice - as.price) * as.goods_nums;
      jsFlow();
    });
    // ShoppList.value.map((item : any, index : number) => {
      console.log('123456789')
      ShoppList.value.splice(ShoppList.value.indexOf(id), 1);
      ShoppingList.value.map((items, indexs) => {
        if (items.store_id == id) {
          ShoppingList.value.splice(indexs, 1);
          items.goods_list = [];
        }
      });
    // });
  }

  /**
   * @param {Object} storeId 店铺ID
   * @param {Object} id  商品iD
   * @param {Object} price 商品价格
   * @param {Object} cost  商品原价
   * @param {Object} num   商品数量
   */
  function commodity(storeId : number, id : number, price : number, cost : number, num : number, name : string) {
    console.log(storeId);
    shopText.value = name;
    console.log(JSON.stringify(ShoppingList.value));
    var goodsList = carAll.value.filter((as) => as.store_id == storeId)[0].goods_list;
    if (ShoppingList.value.length > 0) {
      console.log(ShoppingList.value.find((as) => as.store_id == storeId));
      if (!ShoppingList.value.find((as) => as.store_id == storeId) && !show.value) {
        errorToast('当前购物车只能购买同一家商品');
        return;
      }
      ShoppingList.value.map((item, index) => {
        if (item.store_id == storeId) {
          console.log('操作当前店铺商品');
          console.log(JSON.stringify(item.goods_list));
          if (item.goods_list.indexOf(id) == -1) {
            console.log('添加当前店铺商品');
            item.goods_list.push(id);
            shopNumber(storeId);
            if (item.goods_list.length == goodsList.length) {
              ShoppList.value.push(storeId);
            }
            total.value = total.value + price * num;
            Discount.value = Discount.value + (cost - price) * num;
            jsFlow();
          } else {
            Select.value = false;
            console.log('减少存在当前店铺商品');
            item.goods_list.map((items : any, indexs : number) => {
              if (items == id) {
                item.goods_list.splice(indexs, 1);
                shopNumber(storeId);
                var nums = ShoppList.value.indexOf(storeId);
                if (item.goods_list.length == 0) {
                  if (nums != -1) {
                    ShoppList.value.splice(nums, 1);
                  }
                  ShoppingList.value.splice(index, 1);
                } else if (item.goods_list.length != goodsList.length && nums != -1) {
                  ShoppList.value.splice(nums, 1);
                }
                total.value = total.value - price * num;
                Discount.value = Discount.value - (cost - price) * num;
                jsFlow();
              }
            });
          }
        } else if (!ShoppingList.value.find((as) => as.store_id == storeId)) {
          var goods = [];
          goods.push(id);
          var obj = {
            store_id: storeId,
            goods_list: goods,
          };
          ShoppingList.value.push(obj);
          shopAll(storeId, goodsList);
        }
      });
    } else {
      addShop(storeId, id, price, num, cost, goodsList);
    }
  }
  function shopAll(storeId : number, goodsList : any) {
    ShoppingList.value.map((item) => {
      if (item.goods_list.length == goodsList.length) {
        ShoppList.value.push(storeId);
        if (ShoppList.value.length == carAll.value.length) {
          Select.value = true;
        } else {
          Select.value = false;
        }
      }
    });
  }
  /**
   * @param {String} storeId 店铺ID
   * @param {String} id  商品iD
   * @param {String} price 商品价格
   * @param {String} cost  商品原价
   * @param {String} num   商品数量
   * @param {Array} goodsList  当前店铺的所有商品
   */
  function addShop(storeId : number, id : number, price : number, num : number, cost : number, goodsList : any) {
    var goods = [];
    goods.push(id);
    console.log(goods);
    var obj = {
      store_id: storeId,
      goods_list: goods,
    };
    ShoppingList.value.push(obj);
    shopNumber(storeId);
    total.value = total.value + price * num;
    Discount.value = Discount.value + (cost - price) * num;
    var shopList = ShoppingList.value.filter((as) => as.store_id == storeId)[0].goods_list;
    if (shopList.length == goodsList.length) {
      ShoppList.value.push(storeId);
    }
    jsFlow();
  }
  /**
   * @param {Object} num 修改商品信息
   * @param {String} num.shopID 店铺ID
   * @param {String} num.id 商品ID
   * @param {String} num.num 商品数量
   */
  function ModifyCart(num : any) {
    console.log(JSON.stringify(num));
    init(num);
  }
  /**
   * @param {Object} num 当前商品信息
   * @param {String} num.shopID 店铺ID
   * @param {String} num.id 商品ID
   * @param {String} num.num 商品数量
   */
  function moneyFor(num : any) {
    const goods = carAll.value.filter((item) => item.store_id == num.shopID)[0].goods_list.find((as : any) => as.id == num.id);
    if (ShoppingList.value.length > 0) {
      ShoppingList.value.map((item) => {
        if (item.store_id == num.shopID) {
          item.goods_list.map((items : any) => {
            if (items == num.id) {
              total.value = total.value + (Number(goods.goods_nums) - Number(num.num)) * goods.price;
              Discount.value =
                Discount.value + (goods.oprice - goods.price) * (Number(goods.goods_nums) - Number(num.num));
              jsFlow();
            }
          });
        }
      });
    }
  }
  /**
   * @param {Object} storeId 店铺ID
   */
  function shopNumber(storeId) {
    if (!show.value) {
      return;
    }
    const car = carAll.value.filter((item) => item.store_id == storeId)[0].goods_list;
    const god = ShoppingList.value.filter((item) => item.store_id == storeId)[0].goods_list;
    if (car.length == god.length) {
      ShoppList.value.push(storeId);
    } else {
      ShoppList.value.splice(ShoppList.value.indexOf(storeId), 1);
    }
  }
  //计算购物车金额精准度
  function jsFlow() {
    var v1 = total.value.toFixed(2);
    var v2 = Discount.value.toFixed(2);
    total.value = Math.floor(parseFloat(v1 * 100)) / 100;
    Discount.value = Math.floor(parseFloat(v2 * 100)) / 100;
  }

  function supervise() {
    ShoppList.value = [];
    ShoppingList.value = [];
    total.value = 0;
    Discount.value = 0;
    show.value = !show.value;
    title.value = show.value ? '删除' : '结算';
    Select.value = false;
  }

  function SelectAll() {
    // Select.value = !Select.value
    if (!Select.value) {
      Select.value = true;
      if (ShoppingList.value.length < 1) {
        carAll.value.map((item) => {
          ShoppList.value.push(item.store_id);
          var goods = [];
          item.goods_list.forEach((as) => {
            goods.push(as.id);
          });
          var obj = {};
          obj.store_id = item.store_id;
          obj.goods_list = goods;
          ShoppingList.value.push(obj);
          console.log(ShoppingList.value);
        });
      }
    } else {
      Select.value = false;
      ShoppingList.value = [];
      ShoppList.value = [];
    }
  }
  /**
   * 购物车结算
   */
  function submit() {
    if (!show.value) {
      if (ShoppingList.value.length < 1) {
        errorToast('请选择您要结算的商品');
        return;
      }
      showLoading();
      if (!repeat.value) {
        return;
      }
      repeat.value = false;
      const payload = {
        user_id: driver_id,
        store_id: ShoppingList.value[0].store_id,
        cart_ids: ShoppingList.value[0].goods_list.join(','),
      };
      toPublish('store/addShopOrderByCart', payload, (obj : any) => {
        const { code, msg, data } = obj;
        console.log(JSON.stringify(data));
        if (code === 1) {
          repeat.value = true;
          successToast(msg);
          uni.navigateTo({
            url: '/pages/shopp/sureOrder?id=' + data.order_id + '&shopName=' + shopText.value,
          });
        } else {
          repeat.value = true;
          errorToast(msg);
        }
      });
    } else {
      var idArry = [];
      ShoppingList.value.map((item) => {
        console.log(item.goods_list);
        idArry = [...idArry, ...item.goods_list];
      });
      if (ShoppingList.value.length < 1) {
        errorToast('请选择您要删除的商品');
        return;
      }
      showLoading();
      if (!repeat.value) {
        return;
      }
      repeat.value = false;
      const payload = {
        ids: idArry.join(','),
      };
      toPublish('store/delCartNums', payload, (obj : any) => {
        const { code, msg } = obj;
        if (code === 1) {
          repeat.value = true;
          Select.value = false;
          successToast(msg);
          init('1');
        } else {
          repeat.value = true;
          errorToast(msg);
        }
      });
    }
  }
</script>

<style scoped lang="less">
  @import url('../shopp/less/myCar.less');
</style>